package com.start.common.dataRule;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.start.common.constant.StartConstant;
import com.start.common.entity.StartBaseMenuDataRules;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;


import java.util.List;

public abstract class AbstractCommonQuery<Z extends Object> extends QueryWrapper<Z> implements BaseQuery {

    protected HttpServletRequest request;

    public AbstractCommonQuery(HttpServletRequest request) {
        this.request = request;
    }


    /**
     * 解析数据权限
     */
    @Override
    public final void analysisDataPermission() {
        Object component = request.getAttribute(StartConstant.DataRule.key);
        if (component == null) return;
        String key = component.toString();
        if (StringUtils.isEmpty(key)) return;
        Object attribute = request.getAttribute(StartConstant.DataRule.rulesKey);
        List<StartBaseMenuDataRules> dataRulesVos = JSONArray.parseArray(attribute.toString(), StartBaseMenuDataRules.class);
        checkLegitimacy(dataRulesVos);
        for (StartBaseMenuDataRules vo : dataRulesVos) {
            DataRuleConditionEnum dataRuleConditionEnum = DataRuleConditionEnum.create(vo.getRuleCondition());
            if (dataRuleConditionEnum == null) continue;
            String columnName = vo.getRuleColumnName();
            if (enableHumpNaming()) {
                columnName = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(columnName);
            }
            constructorCondition(columnName, vo.getRuleColumnValue(), dataRuleConditionEnum, enableHumpNaming());
        }
    }




    /**
     * 检查合法性
     *
     * @param dataRulesVos
     */
    public abstract void checkLegitimacy(List<StartBaseMenuDataRules> dataRulesVos);

    /**
     * 构建条件
     *
     * @param columnName
     * @param columnValue
     * @param conditionEnum
     * @param enableHumpNaming
     */
    protected abstract void constructorCondition(String columnName,
                                                 String columnValue,
                                                 DataRuleConditionEnum conditionEnum,
                                                 boolean enableHumpNaming);
}
